import { get, post } from "./ajax.js";
import { getUrlParam, openwin } from "./fn.js";

var getWhereData = (data = {}) => {
    return {formdata: data}
}

var createTable = (options) => {
    let elem = options.elem ? options.elem : '#currentTableId',
        url = options.url ? options.url : '',
        where = options.where ? options.where : {},
        headers = options.headers ? options.headers : {},
        toolbar = options.toolbar ? options.toolbar : '#toolbarDemo',
        skin = options.skin ? options.skin : '',
        page = options.page ? options.page : true,
        limit = options.limit ? options.limit : 15,
        limits = options.limits ? options.limits : [15,30,50,80,100],
        cols = options.cols ? options.cols : []

    let mytable = layui.table.render({
        elem: elem,
        url: url,
        method: 'get',
        where: getWhereData(where),
        headers: headers,
        //开启头部工具栏，并为其绑定左侧模板,
        toolbar: toolbar, 
        skin: skin,
        page: page,
        limit: limit,
        limits: limits,
        cols: [cols],
        response: {
            statusName: 'code', //规定返回的状态码字段为code
            statusCode: 200 //规定成功的状态码味200
        },
        done:function(res,curr,count){
    
        },
        parseData:function(res) {
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "data": res.data.data, //解析数据列表
                "count": res.data.total, //解析数据长度
            }
        },
    });

    // 重载表格
    reloadTable(mytable)
}

var reloadTable = (table) => {
    layui.form.on('submit(data-search-btn)', function(data) {
        //这里以搜索为例
        table.reload({
            where: getWhereData(data.field),
            page: {
                curr: 1  //重新从第 1 页开始
            },
        });

        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
}

var listenTableOnToolbar = (options) => {
    //头工具栏事件
    layui.table.on('toolbar(currentTableFilter)', function(obj){
        var checkStatus = layui.table.checkStatus(obj.config.id);
        console.log(checkStatus);
        switch(obj.event){
            case 'add':
                openwin('添加', 'save.html', {area: (options.save && options.save.area) ? options.save.area : 'mini'})
                break;
        };
    });
}

var listenTableOnRow = (options) => {
    layui.table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data
        var id = data.id
        switch(obj.event){
            case 'delete':case 'del':
                layer.confirm('你确定要操作吗？', {icon: 7, title:'提示'}, function(index){
                    //do something
                    var url = ''
                    if (options.delete_url) {
                        url = options.delete_url
                    }else if (options.url) {
                        url = options.url.replace("getList", "delete");
                    }

                    layui.layer.load(2)
                    post(url, {id: id}, res => {
                        layui.layer.closeAll();
    
                        if(res.code == 200){
                            layer.msg(res.msg, {icon:6, time:1500},function(){});
                            setTimeout(function() {
                                // 窗口的父窗口刷新，当前窗口关闭
                                window.location.reload();
                            }, 1000)
                        }else{
                            layer.msg(res.msg);
                        }
                    })
                });
                break;
            case 'edit':
                openwin('编辑', 'save.html?id='+data.id, {area: (options.save && options.save.area) ? options.save.area : 'mini'})
                break
        }
    });
}

var getList = (options) => {
    // 創建表格
    createTable(options)
    // 监听头工具条事件
    listenTableOnToolbar(options)
    // 监听行操作
    listenTableOnRow(options)
}

var saveOne = (options) => {
    // 监听提交
    layui.form.on('submit(formDemo)', function(data) {
        var postdata = data.field

        if (options.before) {
            var postdata2 = options.before(postdata)
            if (postdata2 === false) {
                return false;
            }else if (postdata2) {
                postdata = postdata2
            }
        }

        var loading = layer.load(2, {
            shade: [0.3, '#fff']
        });
        
        post(options.url, postdata, json => {
            layer.close(loading);

            if(json.code == 201){
                // 自定义失败执行
                if (options.fail) {
                    options.fail(json);
                    return false;
                }
                
                layer.msg(json.msg);
                return;
            }else{
                // 自定义成功执行
                if (options.success) {
                    options.success(json);
                    return false;
                }

                layer.msg(json.msg, {icon:6,time:1500},function(){});
                setTimeout(function() {
                    // 窗口的父窗口刷新，当前窗口关闭
                    window.parent.location.reload();
                }, 1000)
            }
        }) 

        return false;
    });
}

var getData = (options) => {
    var id = getUrlParam('id');

    layer.load(2)
    get(options.url, {id: id}, json => {
        layer.closeAll();
          
        // 自定义成功执行
        if (options.success) {
            options.success(json);
            return false;
        }
        
        if (json && json.data) {
            layui.form.val("formTest", json.data);
        }
    })
}


export {getList,saveOne,getData}